window.onload = function () {
  let login = JSON.parse(localStorage.getItem('login'))
  if (login == 1) {
    alert('请先登录')
    window.location.href = 'login.html'
  }
}
let id
// 判断考生是不是有考试，从登录的login数组判断
let loginArr = JSON.parse(localStorage.getItem('login')) || []
let examArr = JSON.parse(localStorage.getItem('exam')) || []
let exam = []
for (mes of examArr) {
  // console.log(loginArr[0].username)
  // console.log(mes)
  if (mes.user.indexOf(loginArr[0].username) !== -1) {
    console.log(1)
    if (mes.examState === '开启') {
      exam.push(mes)
    }
  }
}
console.log(exam)
// 考试列表渲染
let tbody = document.querySelector('.add-cue')
function examListXR() {
  let i = 0
  for (mes of exam) {
    i++
    let tr = document.createElement('tr')
    tr.innerHTML = `
  <td>${mes.examID}</td>
  <td>${loginArr[0].username}</td>
  <td>${mes.numbers}</td>
  <td>${mes.limitTime}</td>
  <td>
  <button class='btn' data-id='${i - 1}' disabled >开始考试</button>
  </td>
    `
    id = mes.examID
    tbody.appendChild(tr)
  }
}
examListXR()
//勾选按钮
let btn = document.querySelectorAll('.btn')
let iptck = document.querySelector('#chk')
iptck.addEventListener('click', function () {
  if (this.checked) {
    // console.log('点击')
    for (mes of btn) {
      mes.disabled = false
    }
  } else if (!(this.checked)) {
    // console.log('没点击')
    for (mes of btn) {
      mes.disabled = true
    }
  }
})
// 开始考试按钮
// 定义考试时的索引
tbody.addEventListener('click', function (e) {
  //点击button开始考试
  if (e.target.className === 'btn') {
    const btn = e.target
    console.log(btn)
    //获取最近的tr
    const row = btn.closest('tr')
    // 获取考试的数组
    let examArr = JSON.parse(localStorage.getItem('examResult')) || []
    // 获取表格信息
    const examID = row.children[0].textContent
    id = examID
    const user = row.children[1].textContent
    // 检查考试数组中是否有相同的值
    const examArr1 = examArr.some(item =>
      item.examID == examID &&
      item.user == user
    )
    if (examArr1) {
      alert('该考试已考')
    } else {
      console.log('开始考试')
      // 显示
      document.querySelector('.examBox').style.display = 'flex'
      document.querySelector('.exam-know').style.display = 'none'
      // 考试时间
      let time = document.querySelector('.time')
      // console.log(exam[e.target.dataset.id].limitTime)
      let s = exam[e.target.dataset.id].limitTime * 60
      dsq = setInterval(() => {
        s -= 1
        if (Math.floor(s / 60 % 60) < 10) {
          m = `0${Math.floor(s / 60 % 60)}`
        }
        if (Math.floor(s % 60) < 10) {
          ss = `0${Math.floor(s % 60)}`
        }
        time.innerHTML = `考试时间剩余：0${Math.floor(s / 60 / 60)}:${Math.floor(s / 60 % 60) < 10 ? m : Math.floor(s / 60 % 60)}:${Math.floor(s % 60) < 10 ? ss : Math.floor(s % 60)}`
      }, 1000)
      // 获取题目
      let tm = JSON.parse(localStorage.getItem('TMU'))
      let tmArr = []
      let danxuan = []
      let duoxuan = []
      let tinakong = []
      let jianda = []
      for (mes of tm) {
        // 单选题
        if (exam[e.target.dataset.id].danxuan !== '') {
          if (exam[e.target.dataset.id].danxuan.indexOf(mes.ID) !== -1) {
            danxuan.push(mes)
          }
        }
        // 多选题
        if (exam[e.target.dataset.id].duoxuan !== '') {
          if (exam[e.target.dataset.id].duoxuan.indexOf(mes.ID) !== -1) {
            duoxuan.push(mes)
          }
        }
        // 填空题
        if (exam[e.target.dataset.id].tiankon !== '') {
          if (exam[e.target.dataset.id].tiankon.indexOf(mes.ID) !== -1) {
            tinakong.push(mes)
          }
        }
        // 简答题
        if (exam[e.target.dataset.id].jianda !== '') {
          if (exam[e.target.dataset.id].jianda.indexOf(mes.ID) !== -1) {
            jianda.push(mes)
          }
        }

      }
      tmArr.push(danxuan)
      tmArr.push(duoxuan)
      tmArr.push(tinakong)
      tmArr.push(jianda)
      // console.log(tmArr)
      // 将数组展平变成一维数组
      let tempExam = tmArr.flat()
      // 定义循序
      let arrOrder = ["单选题", "多选题", "填空题", "简答题"]
      // 进行排序,arrOrder.indexOf(a.type)获取a的题型在arrOrder数组中的索引，同理获取b的题型在arrOrder数组中的索引，相减会根据定义的数组循序进行比较之后排序
      tempExam.sort((a, b) => arrOrder.indexOf(a.type) - arrOrder.indexOf(b.type))
      // console.log(tempExam)
      // 创建临时考试题目的本地存储
      localStorage.setItem('tempExam', JSON.stringify(tempExam))
      render(index)
      let arr = JSON.parse(localStorage.getItem('tempExam'))
      let dxtUl = document.querySelector('.dxtUl')
      let duoxtUl = document.querySelector('.duoxtUl')
      let tianktUl = document.querySelector('.tianktUl')
      let jiandatUl = document.querySelector('.jiandatUl')
      for (a in arr) {
        if (arr[a].type === '单选题') {
          console.log('单选题')

          let li = document.createElement('li')
          console.log('单选题:' + a)
          li.innerHTML = +a + 1
          dxtUl.appendChild(li)
        }
        if (arr[a].type === '多选题') {
          console.log('多选题')
          let li = document.createElement('li')
          li.innerHTML = +a + 1
          console.log('多选题:' + a)
          duoxtUl.appendChild(li)
        }
        if (arr[a].type === '填空题') {
          console.log('填空题')
          let li = document.createElement('li')
          li.innerHTML = +a + 1
          console.log('填空题:' + a)
          tianktUl.appendChild(li)
        }
        if (arr[a].type === '简答题') {
          console.log('简答题')
          let li = document.createElement('li')
          li.innerHTML = +a + 1
          console.log('简答题:' + a)
          jiandatUl.appendChild(li)
        }
      }
      addDataID()
    }
    // addDataID()
    return
  }
})
// 交卷
let score = 0
function submit() {
  if (confirm('确认交卷吗？')) {
    saveAnswer(index)
    clearInterval(dsq)
    compute()
    creataObj()
    // location.reload(true)
    document.querySelector('.examBox').style.display = 'none'
    document.querySelector('.achievementsBox').style.display = 'flex'
  }
}
// 获取本地临时题目
let tempExam = JSON.parse(localStorage.getItem('tempExam'))
//先创建几个公共变量
//答案数组
// 单选题答案
let answer = tempExam.map((item) => { return item.Answer })
//序号
let index = 0
//学生答案
let sAnswer = []
// 题目渲染
function render(index) {

  let legend = document.querySelector('legend')
  let div = document.querySelector('#answerblank')
  // if(tempExam[0].length>answerDan.length)
  let arr = JSON.parse(localStorage.getItem('tempExam'))
  //从页面上获取5个元素,设定这5个元素的文本
  if (arr[index].type === '单选题') {
    legend.innerText = '单选题'
    div.innerHTML = `
        <li style="list-style: none;"><input type="checkbox" value="A" name="option" id="A">A：<label for="A"
            id="choice-a"></label></input>
        </li>
        <li style="list-style: none;"><input type="checkbox" value="B" name="option" id="B">B：<label for="B"
            id="choice-b"></label></input>
        </li>
        <li style="list-style: none;"><input type="checkbox" value="C" name="option" id="C">C：<label for="C"
            id="choice-c"></label></input>
        </li>
        <li style="list-style: none;"><input type="checkbox" value="D" name="option" id="D">D：<label for="D"
            id="choice-d"></label></input>
        </li>
        <div class="butns">
          <button id="prev" onclick="prev()">上一题</button>
          <button id="next" onclick="next()">下一题</button>
          <button id="over" onclick="submit()">交卷</button>
        </div>
    `
    let num = document.querySelector('#number')
    let tgs = document.querySelector('#title')
    let as = document.querySelector('#choice-a')
    let bs = document.querySelector('#choice-b')
    let cs = document.querySelector('#choice-c')
    let ds = document.querySelector('#choice-d')
    // console.log('单选题')
    num.innerText = `试题${index + 1}:`
    tgs.innerText = tempExam[index].tg
    as.innerText = tempExam[index].A
    bs.innerText = tempExam[index].B
    cs.innerText = tempExam[index].C
    ds.innerText = tempExam[index].D
    //先把所有的input元素的checked状态恢复为默认的false
    document.querySelectorAll('input[type=checkbox]').forEach(item => {
      item.type = 'radio'
    })
    document.querySelectorAll('input[type=radio]').forEach(item => {
      item.checked = false
    })
  } else if (arr[index].type === '多选题') {
    legend.innerText = '多选题'
    div.innerHTML = `
    <li style="list-style: none;"><input type="radio" value="A" name="option" id="A">A：<label for="A"
        id="choice-a"></label></input>
    </li>
    <li style="list-style: none;"><input type="radio" value="B" name="option" id="B">B：<label for="B"
        id="choice-b"></label></input>
    </li>
    <li style="list-style: none;"><input type="radio" value="C" name="option" id="C">C：<label for="C"
        id="choice-c"></label></input>
    </li>
    <li style="list-style: none;"><input type="radio" value="D" name="option" id="D">D：<label for="D"
        id="choice-d"></label></input>
    </li>
    <div class="butns">
      <button id="prev" onclick="prev()">上一题</button>
      <button id="next" onclick="next()">下一题</button>
      <button id="over" onclick="submit()">交卷</button>
    </div>
`
    let tgs = document.querySelector('#title')
    let as = document.querySelector('#choice-a')
    let bs = document.querySelector('#choice-b')
    let cs = document.querySelector('#choice-c')
    let ds = document.querySelector('#choice-d')
    let num = document.querySelector('#number')
    // console.log('多选题')
    num.innerText = `试题${index + 1}:`
    tgs.innerText = tempExam[index].tg
    as.innerText = tempExam[index].A
    bs.innerText = tempExam[index].B
    cs.innerText = tempExam[index].C
    ds.innerText = tempExam[index].D
    document.querySelectorAll('input[type=radio]').forEach(item => {
      item.type = 'checkbox'
    })
    document.querySelectorAll('input[type=checkbox]').forEach(item => {
      item.checked = false
    })
  } else if (arr[index].type === '填空题') {
    let num = document.querySelector('#number')
    let tgs = document.querySelector('#title')
    num.innerText = `试题${index + 1}:`
    tgs.innerText = tempExam[index].tg
    // console.log('填空')
    legend.innerText = '填空题'
    document.querySelector('#answerblank').innerHTML = `
        <textarea name="" id="tk" style='font-size:16px; margin-bottom:20vh;'></textarea>
        <div class="butns">
          <button id="prev" onclick="prev()">上一题</button>
          <button id="next" onclick="next()">下一题</button>
          <button id="over" onclick="submit()">交卷</button>
        </div>
        `
  } else if (arr[index].type === '简答题') {
    let num = document.querySelector('#number')
    let tgs = document.querySelector('#title')
    num.innerText = `试题${index + 1}:`
    tgs.innerText = tempExam[index].tg
    // console.log('简答')
    legend.innerText = '简答题'
    document.querySelector('#answerblank').innerHTML = `
        <textarea name="" id="jd" style='width:500px;
  height: 300px; font-size:16px;'></textarea>
        <div class="butns">
          <button id="prev" onclick="prev()">上一题</button>
          <button id="next" onclick="next()">下一题</button>
          <button id="over" onclick="submit()">交卷</button>
        </div>
        `
  }
  recoveryAnswer(index)
  // console.log(sAnswer)
}

function next() {
  saveAnswer(index)
  rightLimit()
  index = index >= (tempExam.length - 1) ? (tempExam.length - 1) : ++index
  render(index)
}

function prev() {
  saveAnswer(index)
  rightLimit()
  index = index <= 0 ? 0 : --index
  render(index)
}

// 答案保存函数
function saveAnswer(index) {
  let arr = JSON.parse(localStorage.getItem('tempExam'))
  // 单选题判断：
  if (arr[index].type === '单选题') {
    // console.log('单选题')
    document.querySelectorAll('input[type=radio]').forEach(item => {
      if (item.checked == true) { sAnswer[index] = item.value }
    })
  } else if (arr[index].type === '多选题') {
    // console.log('多选题')
    let str = ''
    document.querySelectorAll('input[type=checkbox]').forEach(item => {
      if (item.checked == true) {
        str += item.value
      }
    })
    sAnswer[index] = str
  } else if (arr[index].type === '简答题') {
    // console.log('简答题')
    sAnswer[index] = document.querySelector('#answerblank #jd').value
  } else if (arr[index].type === '填空题') {
    // console.log('填空题')
    sAnswer[index] = document.querySelector('#answerblank #tk').value
  }

}

// 恢复答案函数
function recoveryAnswer(index) {
  //要实现恢复答案，先从sAnswer数组里获取到对应的索引号的值，然后把这个值和页面上所有的input元素的值进行比对，如果相同就设定该元素的checked属性为真
  let arr = JSON.parse(localStorage.getItem('tempExam'))
  if (arr[index].type === '单选题') {
    document.querySelectorAll('input[type=radio]').forEach(item => {
      if (sAnswer[index] == item.value) { item.checked = true }
    })
  } else if (arr[index].type === '多选题') {
    document.querySelectorAll('input[type=checkbox]').forEach(item => {
      if (sAnswer[index] && sAnswer[index].includes(item.value)) {
        item.checked = true;
      }
    })
  } else if (arr[index].type === '简答题') {
    document.querySelector('#answerblank #jd').value = sAnswer[index] || ''
  } else if (arr[index].type === '填空题') {
    document.querySelector('#answerblank #tk').value = sAnswer[index] || ''
  }

}

// // 右侧考试序号显示函数
function rightLimit() {
  let lis = document.querySelectorAll('.answer-sheets li')
  for (let i = 0; i < sAnswer.length; i++) {
    if (sAnswer[i] !== '' && sAnswer[i] != undefined) { lis[i].classList.add('active') }
  }
}


// 给answer-sheets设置事件委托
document.querySelector('.answer-sheets').addEventListener('click', function (e) {
  if (e.target.tagName === 'LI') {
    console.log(e.target.dataset.id)
    render(e.target.dataset.id - 1)
    rightLimit()
    index = e.target.dataset.id - 1
    saveAnswer(e.target.dataset.id - 1)
  }
})
// 给所有的li标签加上自定义id
function addDataID() {
  let lis = document.querySelectorAll('.answer-sheets li')
  let i = 0
  for (mes of lis) {
    i++
    mes.dataset.id = i
    // console.log(mes)
  }
}

// 计算分数函数
let sum = 0
let dan = 0
let duox = 0
let tiank = 0
let jiand = 0
let py
let all
// console.log(typeof answer.length)
function compute() {
  // 遍历答案数组
  for (let i = 0; i < answer.length; i++) {
    if (answer[i] == sAnswer[i]) {
      sum += (100 / answer.length)
    }
  }
  all = sum.toFixed(1)
  if (all < 60) {
    py = '挂科';
  } else if (all < 75) {
    py = '及格';
  } else if (all < 85) {
    py = '良好';
  } else if (all <= 100) {
    py = '优秀';
  }

  alert(`本次考试你的分为${all},考试的评级为${py}`)
}

// 创建对象来存储考试信息
function creataObj() {
  let arr = JSON.parse(localStorage.getItem('examResult')) || []
  let obj = {
    examID: id,
    user: loginArr[0].username,
    scores: all,
    grade: py
  }
  document.querySelector('.achievements').innerHTML = all
  document.querySelector('.level').innerHTML = py
  arr.push(obj)
  localStorage.setItem('examResult', JSON.stringify(arr))
}



